class Solution {
public:
    vector<int> printMatrix(vector<vector<int> > matrix) {
        vector<int> res;
        if(!matrix.size()) return res;
        int n = matrix.size(),m = matrix[0].size();
        int st[n][m];
        memset(st,0,sizeof st);
        int x = 0,y = 0,d = 1;
        int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
        for(int i = 0;i < m * n;i++){
            res.push_back(matrix[x][y]);
            st[x][y] = 1;
            int nx = x + dx[d],ny = y + dy[d];
            if(nx < 0 || ny < 0 || nx >= n || ny >= m || st[nx][ny]){
                d = (d + 1) % 4;
                nx = x + dx[d],ny = y + dy[d];
            }
            x = nx,y = ny;
        }
        return res;
    }
};